package dk.sdu.flexibus.communications;

import java.util.ArrayList;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;


import android.os.AsyncTask;

public class DropOffPointsProvider {

	private static String SOAP_ACTION = "http://www.madis.dk/Uni/FlexiBus/GetDropOffPoints";
	private static String NAMESPACE = "http://www.madis.dk/Uni/FlexiBus";
	private static String METHOD_NAME = "GetDropOffPoints";
	private static String URL = "http://www.flexibus.madis.dk/WebService.asmx";

	private DropOffPointsListener listener;
	
	public DropOffPointsProvider(DropOffPointsListener listener) {
		super();
		this.listener = listener;
	}

	/** Called when the user clicks the Send button */
	public void sendRequest() {
		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		soapEnvelope.dotNet = true;
		soapEnvelope.setOutputSoapObject(request);
		HttpTransportSE httpTransport = new HttpTransportSE(URL);
		CallServiceTask task = new CallServiceTask(httpTransport, soapEnvelope);
		task.execute();
	}

	private class CallServiceTask extends AsyncTask<Void, Void, String[]> {
		HttpTransportSE httpTransport;
		SoapSerializationEnvelope soapEnvelope;

		public CallServiceTask(HttpTransportSE httpTransport,
				SoapSerializationEnvelope soapEnvelope) {
			super();
			this.httpTransport = httpTransport;
			this.soapEnvelope = soapEnvelope;
		}

		@Override
		protected String[] doInBackground(Void... params) {
			ArrayList<String> result =  new ArrayList<String>();
			try {
				httpTransport.call(SOAP_ACTION, soapEnvelope);
				SoapObject getDropOffPointsResult = (SoapObject) soapEnvelope.getResponse();
				for(int i=0; i<getDropOffPointsResult.getPropertyCount(); i++){
					SoapPrimitive dropOffPoint =(SoapPrimitive) getDropOffPointsResult.getProperty(i);
					result.add(dropOffPoint.toString());
				}
			} catch (Exception exception) {
			}
			return result.toArray(new String[0]);
		}

		// onPostExecute displays the results of the AsyncTask.
		@Override
		protected void onPostExecute(String[] result) {
			listener.setDropoffPoints(result);
		}
	}
}
